#include "Bridger.h"

#include <assert.h>

// base class to bridge between a Reaper object and the Luasphere

//void	*Bridger::theReaperObject;

	Bridger::Bridger(lua_State *L)
	{
		SetReaperObject(NULL);
	}

	void *Bridger::GetReaperObject(void)
	{
		return theReaperObject;
	}

	void Bridger::SetReaperObject(void *ptr)
	{
		theReaperObject = ptr;
	}

void *toReaperObject(lua_State *L, int idx)
{
	void *rop = NULL;

	lua_pushnumber(L, 0);
	if(idx < 0) idx--;	// skip over the zero we just pushed
	lua_gettable(L, idx);
	Bridger **handle = 
					(Bridger **) lua_touserdata(L, -1);
	assert(handle != NULL);
	rop = (*handle)->GetReaperObject();

	return rop;
}

void setupUserdata(lua_State *L, void *reaperObjPtr)
{
	lua_pushnumber(L, 0);					// {self} 0
	lua_gettable(L, -2);					// {self} userdata-from-{self}

	Bridger **handle =				// {self} userdata
					(Bridger **) lua_touserdata(L, -1);
	assert(handle != NULL);

	Bridger *bp = *handle;

	bp->SetReaperObject(reaperObjPtr);

	lua_pop(L, 1);							// {self}
}

// the {self} table must be at the top of the stack

void addToString(lua_State *L, int cf(lua_State *L) )
{
	lua_newtable(L);							//	{self} {}
	lua_pushstring(L, "__tostring");			//  {self} {} "__tostring"
	lua_pushcfunction(L, cf);					//	{self} {} "__tostring" cfunc
	lua_settable(L, -3);						//	{self} {table with __tostring}
	lua_setmetatable(L, -2);					//	{self}
}
